<template>
  <el-dialog
    class="config-dialog-box"
    v-model="isShowDialog"
    title="参数设置"
    width="820"
    center
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-scrollbar class="el-scrollbar-box" height="320px" noresize>
      <el-form class="params-config-box" ref="formRef" :model="form" :rules="formRules">
        <el-row :gutter="17">
          <el-col :span="8">
            <el-form-item label="通讯类型" prop="serialLevel">
              <div class="flex align-center">
                <el-select
                  class="ports-select-box"
                  v-model="form.serialLevel"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="(item, index) in dicts_communication_type"
                    :key="index"
                    :label="item.dictLabel"
                    :value="+item.dictValue"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.serialLevel !== 2">
            <el-form-item label="串口波特率" prop="baudRate">
              <div class="flex align-center">
                <el-select
                  class="ports-select-box"
                  v-model="form.baudRate"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="(item, index) in baudRateList"
                    :key="index"
                    :label="item.dictLabel"
                    :value="+item.dictValue"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.serialLevel === 2">
            <el-form-item label="CAN波特率" prop="canRate">
              <div class="flex align-center">
                <el-select
                  class="ports-select-box"
                  v-model="form.canRate"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="(item, index) in canRateList"
                    :key="index"
                    :label="item.dictLabel"
                    :value="+item.dictValue"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.serialLevel === 2">
            <el-form-item label="帧类型" prop="msgType">
              <div class="flex align-center">
                <el-select
                  class="ports-select-box"
                  v-model="form.msgType"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="(item, index) in msgTypeList"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供电电压" prop="serviceVoltage">
              <div class="flex align-center">
                <el-select
                  class="ports-select-box"
                  v-model="form.serviceVoltage"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="(item, index) in serviceVoltageList"
                    :key="index"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品类" prop="categoryId">
              <div class="flex align-center">
                <el-select
                  class="ports-select-box"
                  v-model="form.categoryId"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                  style="width: 150px"
                  @change="handleSelCategory"
                >
                  <el-option
                    v-for="(item, index) in categoryData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号" prop="computerName">
              <div class="flex align-center">
                <el-select
                  class="ports-select-box"
                  v-model="form.computerName"
                  filterable
                  clearable
                  suffix-icon="CaretBottom"
                  placeholder="请选择"
                  style="width: 150px"
                >
                  <el-option
                    v-for="(item, index) in computerData"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  >
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isShowDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm(formRef)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang='ts' setup>
import { reactive, ref, watch } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { get } from '@renderer/utils/api'

// hooks
import { useCommonTools } from '@renderer/hooks/commonTools'
import { usePortsStore } from '@renderer/stores/portsStore'
import { useMessage } from '@renderer/hooks/message'
const commonTools = useCommonTools()
const portsStore = usePortsStore()
const messageTip = useMessage()

interface RuleForm {
  serialLevel: number
  baudRate: number
  canRate: string
  msgType: string
  serviceVoltage: string
  VLK5Switch: string
  protocolType: string
  categoryId: string
  computerName: string
}

const formRef = ref<FormInstance>()
const isShowDialog = ref(false)
const form = reactive<RuleForm>({
  serialLevel: 1,
  baudRate: 4,
  canRate: '',
  msgType: '',
  serviceVoltage: '',
  VLK5Switch: '',
  protocolType: '',
  categoryId: '',
  computerName: ''
})

const formRules = reactive<FormRules<RuleForm>>({
  serialLevel: [{ required: true, message: '请选择', trigger: 'change' }],
  baudRate: [{ required: true, message: '请选择', trigger: 'change' }],
  canRate: [{ required: true, message: '请选择', trigger: 'change' }],
  msgType: [{ required: true, message: '请选择', trigger: 'change' }],
  serviceVoltage: [{ required: true, message: '请选择', trigger: 'change' }],
  VLK5Switch: [{ required: true, message: '请选择', trigger: 'change' }],
  protocolType: [{ required: true, message: '请选择', trigger: 'change' }],
  categoryId: [{ required: true, message: '请选择', trigger: 'change' }],
  computerName: [{ required: true, message: '请选择', trigger: 'change' }]
})

interface ParamsType {
  dictLabel: string | number
  dictValue: string | number
}
// 通讯类型
const dicts_communication_type = ref<ParamsType[]>([])
// uart波特率
const baudRateList = ref<ParamsType[]>([
  {
    dictLabel: '1200',
    dictValue: 0x01
  },
  {
    dictLabel: '2400',
    dictValue: 0x02
  },
  {
    dictLabel: '4800',
    dictValue: 0x03
  },
  {
    dictLabel: '9600',
    dictValue: 0x04
  },
  {
    dictLabel: '14400',
    dictValue: 0x05
  },
  {
    dictLabel: '19200',
    dictValue: 0x06
  },
  {
    dictLabel: '38400',
    dictValue: 0x07
  },
  {
    dictLabel: '43000',
    dictValue: 0x08
  },
  {
    dictLabel: '57600',
    dictValue: 0x09
  },
  {
    dictLabel: '76800',
    dictValue: 0x0a
  },
  {
    dictLabel: '115200',
    dictValue: 0x0b
  },
  {
    dictLabel: '128000',
    dictValue: 0x0c
  }
])
// can波特率
const canRateList = ref<ParamsType[]>([
  {
    dictLabel: '100K',
    dictValue: 0x01
  },
  {
    dictLabel: '125K',
    dictValue: 0x02
  },
  {
    dictLabel: '150K',
    dictValue: 0x03
  },
  {
    dictLabel: '200K',
    dictValue: 0x04
  },
  {
    dictLabel: '250K',
    dictValue: 0x05
  },
  {
    dictLabel: '300K',
    dictValue: 0x06
  },
  {
    dictLabel: '400K',
    dictValue: 0x07
  },
  {
    dictLabel: '500K',
    dictValue: 0x08
  },
  {
    dictLabel: '600K',
    dictValue: 0x09
  },
  {
    dictLabel: '900K',
    dictValue: 0x0a
  }
])
// 帧类型
const msgTypeList = [
  { dictLabel: '标准帧', dictValue: 1 },
  { dictLabel: '扩展帧', dictValue: 2 }
]

// 供电电压
const serviceVoltageList = [
  { dictLabel: '12V', dictValue: 0 },
  { dictLabel: '24V', dictValue: 1 }
]

// 品类
interface modelType {
  name: string
  id: string
}
const categoryData = ref<modelType[]>([])
// 型号
const computerData = ref<modelType[]>([])

const getDictsData = () => {
  commonTools.getDicts('instrument_communication_type_1').then((res: any) => {
    console.log('instrument_communication_type_1', res)
    dicts_communication_type.value = res.data
  })

  get('/dut/manager').then((res) => {
    categoryData.value = res.data
  })
}

const handleSelCategory = (categoryId) => {
  form.computerName = ''
  computerData.value = []
  get(`/dut/manager/${categoryId}`).then((res) => {
    computerData.value = res.data
  })
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('form', form)
      const CMD_ADDRESS = 0xa6
      let bytesData: any[] = []
      const { baudRate, canRate, msgType, serialLevel, serviceVoltage, computerName } = form

      bytesData = [
        serialLevel,
        serialLevel === 2 ? canRate : baudRate,
        serialLevel === 2 ? msgType : 0,
        serviceVoltage,
        0,
        upgradeType.value === 3 ? 1 : 0,
        0
      ]
      
      const modleNameBytesArr = commonTools.stringToHexArray(computerName)

      portsStore.writeMsg(
        portsStore.cmdSum(CMD_ADDRESS, [
          ...bytesData,
          modleNameBytesArr.length,
          ...modleNameBytesArr
        ])
      )
      portsStore.onDataReceived = (dataHex) => {
        if (dataHex[1] === CMD_ADDRESS) {
          if (dataHex[3] === 1) {
            console.log('结果', dataHex)
            isShowDialog.value = false
            messageTip.success('参数设置成功')
            emit('handleSendParams', {
              result: true
            })
          } else {
            messageTip.error('参数设置失败')
          }
        }
      }
    }
  })
}

const emit = defineEmits(['handleSendParams'])
let upgradeType = ref()
defineExpose({
  isShowDialog,
  upgradeType
})

watch(
  () => isShowDialog.value,
  (isShow) => {
    if (isShow) {
      getDictsData()
    }
  }
)
</script>
  
  <style lang='scss'>
.config-dialog-box {
  box-sizing: border-box;
  background: $default-bg-color;
  border-radius: 10px;

  .el-dialog__header {
    padding-bottom: 20px;

    .el-dialog__title {
      color: #fff;
    }

    .el-dialog__close {
      font-size: 26px;
      font-weight: bold;
      color: #fff;
    }
  }
}
</style>